#include "threadPool.h"
#include <my_header.h>
int initThreadPool(threadPool_t *pthreadPool, int workerNum) {
    pthreadPool->workerNum = workerNum;
    pthreadPool->tidArr =
        (pthread_t *)calloc(pthreadPool->workerNum, sizeof(pthread_t));
    initQueue(&pthreadPool->taskQueue);
    return 0;
}
int configureInit_ip_port_threadNum(char *ip, char *port, char *threadNum) {
    char str[256];
    FILE *configFile = fopen("/configure/netdisk.ini", "r");
    if (configFile == NULL) {
        printf("Failed to open the configuration file!\n");
        exit(-1);
    }
    memset(str, 0, sizeof(str));
    fgets(str, 256, configFile);
    str[strcspn(str, "\n")] = '\0';
    char *p = strstr(str, "=");
    if (p != NULL) {
        p++;
        sprintf(ip, "%s", p);
        printf("ip = %s", ip);
    } else {
        printf("not found =\n");
    }
    memset(str, 0, sizeof(str));
    fgets(str, 256, configFile);
    str[strcspn(str, "\n")] = '\0';
    p = strstr(str, "=");
    if (p != NULL) {
        p++;
        sprintf(port, "%s", p);
        printf("port = %s", port);
    } else {
        printf("not found =\n");
    }
    memset(str, 0, sizeof(str));
    fgets(str, 256, configFile);
    str[strcspn(str, "\n")] = '\0';
    p = strstr(str, "=");
    if (p != NULL) {
        p++;
        sprintf(threadNum, "%s", p);
        printf("threadNum = %s", threadNum);
    } else {
        printf("not found =\n");
    }
}
int main(int argc, char *argv[]) {
    // ./server 192.168.189.128 1234 3
    char ip[20] = {0};
    char port[8] = {0};
    char threadNum[8] = {0};

    configureInit_ip_port_threadNum(ip, port, threadNum);
    /* ARGS_CHECK(argc,4); */
    threadPool_t threadPool;
    int workerNum = atoi(threadNum);
    initThreadPool(&threadPool, workerNum);
    // 初始化tcp
    int sockfd;
    tcpInit(ip, port, &sockfd);
    // 创建子线程
    makeWorker(&threadPool);
    // 监听sockfd
    int epfd = epoll_create(1);
    
    epollAdd(epfd, sockfd);
    struct epoll_event readyset[1024];
    while (1) {
        int readynum = epoll_wait(epfd, readyset, 1024, -1);
        for (int i = 0; i < readynum; ++i) {
            if (readyset[i].data.fd == sockfd) {
                int netfd = accept(sockfd, NULL, NULL);
                printf("1 client connected!\n");
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                enQueue(&threadPool.taskQueue, netfd);
                printf("1 netfd enqueue!\n");
                pthread_cond_signal(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
            }
        }
    }
}
